package com.aaa.tars.service.impl;

import com.aaa.tars.dao.MenuDao;
import com.aaa.tars.entity.Menu;
import com.aaa.tars.entity.User;
import com.aaa.tars.service.MenuService;
import com.aaa.tars.util.CustomException;
import com.aaa.tars.util.ResultStatus;
import com.aaa.tars.vo.TreeNode;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @FileName: MenuServiceImpl
 * @Description:
 * @Author: ghz
 * @CreateTime:2025/8/29 19:38
 * @Version:1.0.0
 */
@Service
public class MenuServiceImpl implements MenuService {
//    依赖注入
//    @Autowired(spring的注解)
    @Resource
    private MenuDao menuDao;

    @Resource
    private HttpSession session;

    // 定义一个集合，用于保存当前节点的子节点
    List<TreeNode> findCurrentTreeNodeChildrenList=new ArrayList<>();
    @Override
    public List<TreeNode> queryTreeData() {
        List<TreeNode> treeNodeList = menuDao.queryAllMenu();
        // 定义返回集合（树形数据）
        List<TreeNode> treeNodeListResult = new ArrayList<>();
        // 判断获取菜单是否为空
        if (!CollectionUtils.isEmpty(treeNodeList)) {
            for (TreeNode treeNode : treeNodeList) {
                // 查找一级菜单（parentId=0）
                if (treeNode.getParentId()==0){
                    treeNodeListResult.add(treeNode);
                    // 调用查找并绑定孩子的方法
                    bindChildren(treeNode,treeNodeList);
                }
            }
        }
        return treeNodeListResult;
    }

    @Override
    public List<TreeNode> queryTreeDataByUserId(Integer userId) {
        List<TreeNode> treeNodeList = menuDao.queryMenuByUserId(userId);
        List<TreeNode> treeNodeListResult = new ArrayList<>();
        if(!CollectionUtils.isEmpty(treeNodeList)){
            for (TreeNode treeNode : treeNodeList) {
                if (treeNode.getParentId()==0){
                    treeNodeListResult.add(treeNode);
                    bindChildren(treeNode,treeNodeList);
                }
            }
        }
        return treeNodeListResult;
    }

    private void bindChildren(TreeNode currentTreeNode, List<TreeNode> treeNodeList){
        for(TreeNode treeNode : treeNodeList){
            if(currentTreeNode.getId()==treeNode.getParentId()){
                List<TreeNode> children = currentTreeNode.getChildren();
                if (children==null){
                    children = new ArrayList<>();
                }
                children.add(treeNode);
                currentTreeNode.setChildren(children);
                bindChildren(treeNode,treeNodeList);
            }
        }
    }

    @Override
    public List<Menu> queryAll() {
        return menuDao.queryAll();
    }
    @Override
    public Menu queryById(Integer menuId) {
        if(menuId==null||menuId<0){
            throw new CustomException(ResultStatus.PARAM_ISNULL.getStatusCode(),ResultStatus.PARAM_ISNULL.getStatusMessage());
        }
        return menuDao.queryById(menuId);
    }

    @Override
    public int insert(Menu menu) {
        // 设置排序
        menu.setOrderNum(0);
        // 设置可见
        menu.setVisible("0");
        //动态获取创建人
        //拿到登录session
        User userInfo = (User) session.getAttribute("userInfo");
        menu.setCreateBy(userInfo.getUserName());
        // 创建角色时设置本地时间
        menu.setCreateTime(LocalDateTime.now());
        //如果插入没有名字报错
        if(menu.getMenuName()==null||menu.getMenuName().equals("")){
            throw new CustomException(ResultStatus.PARAM_ISNULL.getStatusCode(),ResultStatus.PARAM_ISNULL.getStatusMessage());
        }
        //如果前端没有输入parentId，则默认为0
        if(menu.getParentId()==null){
            menu.setParentId(0);
        }
        menu.setCreateTime(LocalDateTime.now());
        return menuDao.insert(menu);
    }

    @Override
    public int update(Menu menu) {
        //如果muneid和parentid相同，则报错
        if(menu.getMenuId().equals(menu.getParentId())){
            //抛出报错信息不能选自身节点为父类节点
            throw new CustomException(1011,"不能选自身节点为父节点");
        }

        // 2. 新增：禁止将当前节点的子节点设为父节点
        // 以当前节点为根节点，查询当前节点所有子节点
        if (menu.getParentId() != null && menu.getParentId() > 0) {
            List<TreeNode> treeNodeList = menuDao.queryAllMenu();
            // 判断获取菜单是否为空
            if (!CollectionUtils.isEmpty(treeNodeList)) {
                for (TreeNode treeNode : treeNodeList) {
                    // 查找一级菜单（parentId=0）
                    if (treeNode.getParentId()==menu.getMenuId()){
                        findCurrentTreeNodeChildrenList.add(treeNode);
                        // 调用查找并绑定孩子的方法
                        findCurrentTreeNodeChildren(treeNode,treeNodeList);
                    }
                }
            }
            System.out.println("findCurrentTreeNodeChildrenList哈哈哈哈哈:"+findCurrentTreeNodeChildrenList);
            for (TreeNode i : findCurrentTreeNodeChildrenList) {
                if (menu.getParentId()==i.getId()){
                    throw new CustomException(1012,"不能选择自身节点的子节点作为父节点");
                }
            }
        }
        //动态获取创建人
        //拿到登录session
        User userInfo = (User) session.getAttribute("userInfo");
        menu.setUpdateBy(userInfo.getUserName());
        // 设置更新时间
        menu.setUpdateTime(LocalDateTime.now());
        return menuDao.update(menu);
    }

    private void findCurrentTreeNodeChildren(TreeNode currentTreeNode, List<TreeNode> treeNodeList){
        for(TreeNode treeNode : treeNodeList){
            if(treeNode.getParentId()==currentTreeNode.getId()){
                findCurrentTreeNodeChildrenList.add(treeNode);
                findCurrentTreeNodeChildren(treeNode,treeNodeList);
            }
        }
    }

    @Override
    public int deleteById(Integer menuId) {
        //如果该菜单menuid为其他菜单parentid，抛出请先删除子菜单错误
        List<Menu> menuList = menuDao.queryAll();
        for (Menu menu : menuList) {
            if(menu.getParentId().equals(menuId)){
                throw new CustomException(1012,"请先删除子菜单");
            }
        }

        // 检查是否是系统关键菜单（不能删除）
        if (menuId == 14 || menuId == 17 || menuId == 18) {
            throw new CustomException(1035, "该菜单为系统关键菜单，不能删除");
        }

        if(menuId==null||menuId<0){
            throw new CustomException(ResultStatus.PARAM_ISNULL.getStatusCode(),ResultStatus.PARAM_ISNULL.getStatusMessage());
        }
        return menuDao.deleteById(menuId);
    }
}
